<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="规则json" prop="rules">
        <div style="position: relative; min-height: 32px; padding-right: 56px;">
          <div v-for="(item, index) in formData.rule" :key="index" style="min-height: 32px;" :style="index + 1 !== formData.rule.length ? 'margin-bottom: 8px;': ''">
            <el-select v-if="index > 0" v-model="item.associationType" placeholder="且/或" style="width: 80px; margin-bottom: 12px" clearable>
              <el-option label="且" value="AND"/>
              <el-option label="或" value="OR"/>
            </el-select>
            <div style="display: flex; align-items: end;">
              <div style="position: relative; width: 100%; min-height: 32px; padding-right: 42px; border: 1px solid #bbb;">
                <div v-for="(item1, index1) in item.rules" :key="index1">
                  <el-select v-if="index1 > 0" v-model="item1.associationType" placeholder="且/或" style="width: 80px;" clearable>
                    <el-option label="且" value="AND"/>
                    <el-option label="或" value="OR"/>
                  </el-select>
                  <div style="display: flex; align-items: center;">
                    <el-input v-model="item1.key" style="width: 200px;" placeholder="设备属性key" clearable />
                    <el-select v-model="item1.type" placeholder="属性类型" clearable>
                      <el-option
                        v-for="(element,index2) in typeList"
                        :key="index2"
                        :label="element.label"
                        :value="element.value"
                      />
                    </el-select>
                    <div v-if="item1.type === 'BETWEEN'" style="display: flex;">
                      <el-input v-model="item1.formValue" placeholder="值a" clearable @blur="handleBlur(item1)" />
                      ~
                      <el-input v-if="item1.type === 'BETWEEN'" v-model="item1.toValue" placeholder="值b" clearable @blur="handleBlur(item1)" />
                    </div>
                    <el-input v-else v-model="item1.value" placeholder="比较值" clearable />
                    <el-button type="danger" @click="removeRule(item, item1)" round>-</el-button>
                  </div>
                </div>
                <el-button @click="addRule(item)" round style="position: absolute; right: 0; bottom: 0;">+</el-button>
              </div>
              <el-button @click="removeRuleGroup(item)" type="danger" round>-组</el-button>
            </div>
          </div>
          <el-button v-if="formData.rule.length > 0" style="position: absolute; right: 0; bottom: 0; display: flex;" @click="addRuleGroup" round>+组</el-button>
          <el-button v-else @click="addRuleGroup" round>+组</el-button>
        </div>
      </el-form-item>
      <el-form-item label="报警级别" prop="level">
        <el-input v-model="formData.level" placeholder="请输入报警级别" />
      </el-form-item>
      <el-form-item label="详情" prop="detail">
        <el-input v-model="formData.detail" placeholder="请输入详情" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { VacuumAlarmsRuleApi } from '@/api/vs/vacuumalarmsrule'

/** 报警规则 表单 */
defineOptions({ name: 'VacuumAlarmsRuleForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  rule: [],
  level: undefined,
  detail: undefined,
})
const formRules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  rule: [{ required: true, message: '规则json不能为空', trigger: 'blur' }],
  level: [{ required: true, message: '报警级别不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const res = await VacuumAlarmsRuleApi.getVacuumAlarmsRule(id)
      formData.value = res
      formData.value.detail = getStringAfterDetail(formData.value.detail)
      formData.value.rule = JSON.parse(formData.value.rule).rules.map((item)=>{
        return {
          ...item,
          rules: item.rules.map((item1)=>{
            return {
              ...item1,
              formValue: getStringBeforeFirstComma(item1.value),
              toValue: getStringAfterFirstComma(item1.value),
            }
          }),
        }
      })
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
      rules: formData.value.rule,
      detail: `{{device}}${formData.value.detail}`
    }
    if (formType.value === 'create') {
      await VacuumAlarmsRuleApi.createVacuumAlarmsRule(data)
      message.success(t('common.createSuccess'))
    } else {
      await VacuumAlarmsRuleApi.updateVacuumAlarmsRule(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    rule: [],
    level: undefined,
    detail: undefined,
  }
  formRef.value?.resetFields()
}

// 运算符数组
const typeList = ref([
  { label: '等于', value: 'EQ' },
  { label: '不等于', value: 'NE' },
  { label: '大于', value: 'GT' },
  { label: '大于等于', value: 'GE' },
  { label: '小于', value: 'LT' },
  { label: '小于等于', value: 'LE' },
  { label: '介于', value: 'BETWEEN' },
  { label: '包含', value: 'CONTAIN' },
  { label: '不包含', value: 'NOT_CONTAIN' },
])

// 点击添加规则按钮触发
const addRule = (item) => {
  item.rules.push({
    key: '',
    type: '',
    value: '',
    associationType: 'AND',
    rules: []
  })
}

// 点击删除规则按钮触发
const removeRule = (item, item1) => {
  item.rules = item.rules.filter((res)=>{
    return res !== item1
  })
}

// 点击添加规则组按钮触发
const addRuleGroup = () => {
  formData.value.rule.push({
    associationType: 'AND',
    rules: []
  })
}

// 点击删除规则组按钮触发
const removeRuleGroup = (item) => {
  formData.value.rule = formData.value.rule.filter((res)=>{
    return res !== item
  })
}

// 介于值修改触发
const handleBlur = (item1) => {
  item1.value = `${item1.formValue} | ${item1.toValue}`
}

// 截取指定符号前的字符串
const getStringBeforeFirstComma = (str) => {
    return str.split(' | ')[0];
}

// 截取指定符号后的字符串
const getStringAfterFirstComma = (str) => {
    return str.split(' | ')[1];
}

// 截取指定符号后的字符串
const getStringAfterDetail = (str) => {
    return str.split('{{device}}')[1];
}
</script>